window.addEventListener('load', () => {
  const container = document.querySelector('.scroll-container')

  const imgs = ['../public/img/1.jpg', '../public/img/2.jpg', '../public/img/3.jpg']

  let curIndex = 0
  let isAnimating = false

  function createElement(index, className) {
    const div = document.createElement('div')
    div.className = `item ${className}`
    const img = document.createElement('img')
    img.src = imgs[index]
    div.appendChild(img)
    return div
  }

  function resetElements() {
    container.innerHTML = ''

    container.appendChild(createElement(curIndex, 'cur'))

    if (curIndex > 0) {
      const prevIndex = curIndex - 1
      container.appendChild(createElement(prevIndex, 'prev'))
    }

    if (curIndex < imgs.length - 1) {
      const nextIndex = curIndex + 1
      container.appendChild(createElement(nextIndex, 'next'))
    }
  }

  container.addEventListener('wheel', e => {
    if (isAnimating) return

    e.preventDefault()

    if (e.deltaY > 0) {
      if (curIndex >= imgs.length - 1) return
      isAnimating = true
      container.classList.add('scroll-down')
    } else if (e.deltaY < 0) {
      if (curIndex <= 0) return
      isAnimating = true
      container.classList.add('scroll-up')
    }
  })

  container.addEventListener('transitionend', () => {
    if (!isAnimating) return

    if (container.classList.contains('scroll-down')) {
      curIndex++
    } else if (container.classList.contains('scroll-up')) {
      curIndex--
    }

    resetElements()
    container.className = 'scroll-container'
    isAnimating = false
  })

  resetElements()
})
